// 添加MDC对话框组件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/ui/setting/setting_page4_mdc.dart';
import 'package:flutter_deer/util/toast_utils.dart';

class AddMdcDialog extends StatefulWidget {
  const AddMdcDialog({super.key, this.item, required this.onAdd});

  final MdcSetBean? item;
  final ValueChanged<MdcSetBean> onAdd;

  @override
  State<AddMdcDialog> createState() => _AddMdcDialogState();
}

class _AddMdcDialogState extends State<AddMdcDialog> {
  final TextEditingController _ipController = TextEditingController();
  final TextEditingController _portController = TextEditingController();
  int _selectedConnectionType = 1; // 默认选中第一个
  bool _isLevelGaugeEnabled = false;

  @override
  void initState() {
    super.initState();
    // 如果是编辑模式，初始化数据
    if (widget.item != null) {
      _ipController.text = widget.item!.ip;
      _portController.text = widget.item!.port.toString();
      _isLevelGaugeEnabled = widget.item!.needLevelGauge;
    } else {
      // 添加模式，默认端口6000
      _portController.text = '6000';
      _ipController.text = '192.168.';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(4),
      ),
      child: Container(
        width: 450,
        padding: const EdgeInsets.all(18),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题
            const Text(
              '增加/编辑集线器',
              style: TextStyle(
                fontSize: 24,
                color: Color(0xFF222222),
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 15),

            // IP输入
            _buildInputRow('集线器IP', _ipController, true),

            const SizedBox(height: 10),

            // 端口输入
            _buildPortInputRow(),

            const SizedBox(height: 10),

            // 连接方式
            _buildConnectionTypeSelector(),

            const SizedBox(height: 10),

            // 液位仪开关
            _buildLevelGaugeSwitch(),

            const SizedBox(height: 15),

            // 按钮行
            _buildButtonRow(),
          ],
        ),
      ),
    );
  }

  /// 构建输入行
  Widget _buildInputRow(String label, TextEditingController controller, bool isIP) {
    return Row(
      children: [
        SizedBox(
          width: 80,
          child: Text(
            label,
            style: const TextStyle(
              fontSize: 15,
              color: Color(0xFF222222),
            ),
          ),
        ),
        const SizedBox(width: 5),
        Expanded(
          child: Stack(
            alignment: Alignment.centerRight,
            children: [
              TextField(
                controller: controller,
                keyboardType: isIP ? const TextInputType.numberWithOptions(decimal: true) : TextInputType.number,
                decoration: InputDecoration(
                  hintText: isIP ? '请输入' : '6000',
                  hintStyle: const TextStyle(color: Color(0xFF333333)),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: const BorderSide(color: Color(0xFFCCCCCC)),
                  ),
                  contentPadding: const EdgeInsets.only(left: 15, right: 44),
                ),
                inputFormatters: isIP
                    ? [
                        // 只允许输入数字和点
                        FilteringTextInputFormatter.allow(RegExp(r'[0-9.]')),
                      ]
                    : [
                        // 只允许输入数字
                        FilteringTextInputFormatter.digitsOnly,
                        // 限制长度为5
                        LengthLimitingTextInputFormatter(5),
                      ],
              ),
              // 清除按钮
              if (controller.text.isNotEmpty)
                IconButton(
                  onPressed: () {
                    controller.clear();
                    setState(() {});
                  },
                  icon: const Icon(Icons.clear, size: 20),
                  padding: const EdgeInsets.all(10),
                ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建端口输入行
  Widget _buildPortInputRow() {
    return Row(
      children: [
        const SizedBox(
          width: 80,
          child: Text(
            '集线器端口',
            style: TextStyle(
              fontSize: 15,
              color: Color(0xFF222222),
            ),
          ),
        ),
        const SizedBox(width: 5),
        Expanded(
          child: Stack(
            alignment: Alignment.centerRight,
            children: [
              TextField(
                controller: _portController,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  hintText: '',
                  hintStyle: TextStyle(color: Color(0xFF333333)),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    borderSide: BorderSide(color: Color(0xFFCCCCCC)),
                  ),
                  contentPadding: EdgeInsets.only(left: 15, right: 44),
                ),
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(5),
                ],
              ),
              // 清除按钮
              if (_portController.text.isNotEmpty)
                IconButton(
                  onPressed: () {
                    _portController.clear();
                    setState(() {});
                  },
                  icon: const Icon(Icons.clear, size: 20),
                  padding: const EdgeInsets.all(10),
                ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建连接方式选择器
  Widget _buildConnectionTypeSelector() {
    final List<String> connectionTypes = ['协议', '集线器HB', '集线器Json'];

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Padding(
          padding: EdgeInsets.only(top: 10),
          child: Text(
            '连接方式',
            style: TextStyle(
              fontSize: 15,
              color: Color(0xFF222222),
            ),
          ),
        ),
        const SizedBox(width: 5),
        Expanded(
          child: Wrap(
            spacing: 5,
            runSpacing: 5,
            children: List.generate(connectionTypes.length, (index) {
              final int value = index + 1;
              return Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Radio<int>(
                    value: value,
                    groupValue: _selectedConnectionType,
                    onChanged: (int? value) {
                      setState(() {
                        _selectedConnectionType = value!;
                        if (_selectedConnectionType == 1) {
                          _portController.text = '6000';
                        }
                        if (_selectedConnectionType == 3) {
                          _portController.text = '5001';
                        }
                      });
                    },
                  ),
                  Text(
                    connectionTypes[index],
                    style: const TextStyle(fontSize: 15),
                  ),
                ],
              );
            }),
          ),
        ),
      ],
    );
  }

  /// 构建液位仪开关
  Widget _buildLevelGaugeSwitch() {
    return Row(
      children: [
        const Text(
          '打开液位仪',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF222222),
          ),
        ),
        const Spacer(),
        Switch(
          value: _isLevelGaugeEnabled,
          onChanged: (bool value) {
            setState(() {
              _isLevelGaugeEnabled = value;
            });
          },
          activeColor: Colors.blue,
        ),
      ],
    );
  }

  /// 构建按钮行
  Widget _buildButtonRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 取消按钮
        SizedBox(
          width: 130,
          height: 44,
          child: OutlinedButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            style: OutlinedButton.styleFrom(
              side: const BorderSide(color: Color(0xFF13345F)),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
            ),
            child: const Text(
              '取消',
              style: TextStyle(
                fontSize: 18,
                color: Color(0xFF222222),
              ),
            ),
          ),
        ),
        const SizedBox(width: 15),
        // 确定按钮
        SizedBox(
          width: 130,
          height: 44,
          child: ElevatedButton(
            onPressed: () {
              // 验证输入
              if (_ipController.text.isEmpty || _portController.text.isEmpty) {
                Toast.show('请输入IP地址和端口');
                return;
              }
              // 判断ip是否合法
              if (!_isValidIp(_ipController.text)) {
                Toast.show('请输入正确的IP地址');
                return;
              }
              final mdcSetBean = MdcSetBean(
                ip: _ipController.text,
                port: int.parse(_portController.text),
                linkType: _selectedConnectionType,
                needLevelGauge: _isLevelGaugeEnabled,
              );
              widget.onAdd.call(mdcSetBean);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF13345F),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(5),
              ),
            ),
            child: const Text(
              '确定',
              style: TextStyle(
                fontSize: 18,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // _isValidIp
  bool _isValidIp(String ip) {
    final RegExp ipRegex = RegExp(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$');
    return ipRegex.hasMatch(ip);
  }
}
